<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="批次号" prop="batchNumber">
        <el-input v-model="queryParams.batchNumber" placeholder="请输入批次号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="物料编码" prop="materialCode">
        <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="物料类型" prop="materialType">
        <el-select v-model="queryParams.materialType" placeholder="请选择物料类型" filterable clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.MATERIAL_TYPE)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="物料状态" prop="materialState">
        <el-select v-model="queryParams.materialState" placeholder="请选择物料状态" filterable clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.MATERIAL_STATE)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>

      </el-form-item>
      <el-form-item label="仓库" prop="warehouseId">
        <treeselect v-model="queryParams.warehouseId" :options="warehouseTree" :normalizer="normalizerW"
                    placeholder="选择仓库" style="width: 200px" @select="onWarehouseChange"/>
      </el-form-item>
      <el-form-item label="库位" prop="locationId">
        <el-select v-model="queryParams.locationId" placeholder="请选择库位" clearable size="small"
                   style="width: 100%" @change="handleQuery">
          <el-option v-for="location in locationList" :key="location.id" :label="location.storageLocationName"
                     :value="location.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="加工属性" prop="processingAttributes">
        <el-select v-model="queryParams.processingAttributes" placeholder="请选择加工属性" filterable clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.PROCESSING_ATTRIBUTES)"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="炉号" prop="stoveCode">
        <el-input v-model="queryParams.stoveCode" placeholder="请输入炉号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="模号" prop="patternNumber">
        <el-input v-model="queryParams.patternNumber" placeholder="请输入模号" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="生产计划号" prop="productionCode">
        <el-input v-model="queryParams.productionCode" placeholder="请输入生产计划号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="转码前追溯码" prop="frontRetrospectCode">
        <el-input v-model="queryParams.frontRetrospectCode" placeholder="请输入转码前追溯码" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="追溯码" prop="retrospectCode">
        <el-input v-model="queryParams.retrospectCode" placeholder="请输入追溯码" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
                   v-hasPermi="['storage:material:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['storage:material:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['storage:material:delete']"
        >
          批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="60"/>
      <el-table-column label="批次号" align="center" prop="batchNumber" />
      <el-table-column label="物料编码" align="center" prop="materialCode" />
      <el-table-column label="物料名称" align="center" prop="materialName" width="200" show-overflow-tooltip/>
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="物料类型" align="center" prop="materialType" />
      <el-table-column label="物料状态" align="center" prop="materialState" >
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.MATERIAL_STATE, scope.row.materialState) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="库位" align="center" prop="locationName" />
      <el-table-column label="加工属性" align="center" prop="processingAttributes" >
      <template v-slot="scope">
        <span>{{ getDictDataLabel(DICT_TYPE.PROCESSING_ATTRIBUTES, scope.row.processingAttributes) }}</span>
      </template>
      </el-table-column>
      <el-table-column label="生产计划号" align="center" prop="productionCode" />
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
                     v-hasPermi="['storage:material:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['storage:material:delete']">删除
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!-- 对话框(添加 / 修改) -->
    <MaterialForm ref="formRef" @success="getList"/>
  </div>
</template>

<script>
import * as MaterialApi from '@/api/storage/material';
import * as WarehouseApi from "@/api/storage/warehouse";
import * as LocationApi from "@/api/storage/location";
import MaterialForm from './MaterialForm.vue';
import {getDictDatas, getDictDataLabel, DICT_TYPE} from '@/utils/dict'
import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: "Material",
  components: {
    MaterialForm,
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓储物料表	列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 仓库树数据
      warehouseTree: [],
      // 库位列表
      locationList: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        batchNumber: null,
        materialCode: null,
        quantity: null,
        unit: null,
        materialType: null,
        materialState: null,
        warehouseId: null,
        locationId: null,
        grnCode: null,
        processingAttributes: null,
        remark: null,
        stoveCode: null,
        patternNumber: null,
        productionCode: null,
        frontRetrospectCode: null,
        retrospectCode: null,
        createTime: [],
      },
    };
  },
  created() {
    this.getList();
    this.getWarehouseTree();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await MaterialApi.getMaterialPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除仓储物料表	编号为"' + id + '"的数据项?')
      try {
        await MaterialApi.deleteMaterial(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除仓储物料表   */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await MaterialApi.deleteMaterialList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有仓储物料表\t数据项?');
      try {
        this.exportLoading = true;
        const data = await MaterialApi.exportMaterialExcel(this.queryParams);
        this.$download.excel(data, '仓储物料表\t.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },

    /** 获取仓库树数据 */
    async getWarehouseTree() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 1000
        };
        const res = await WarehouseApi.getWarehousePage(params);
        this.warehouseTree = res.data;
      } catch (error) {
        console.error('获取仓库树数据失败:', error);
      }
    },

    /** 树节点标准化处理 */
    normalizerW(node) {
      const result = {
        id: node.id,
        label: node.warehouseName,
        children: undefined
      };
      // 只有当children存在且不为undefined且长度大于0时才添加该字段
      if (node.children && node.children.length > 0) {
        result.children = node.children;
      }
      return result;
    },

    /** 仓库选择变化时触发 */
    async onWarehouseChange(warehouseId) {
      this.queryParams.locationId = null;
      if (warehouseId) {
        await this.getLocationList(warehouseId.id);
      } else {
        this.locationList = [];
      }
    },

    /** 根据仓库ID获取库位列表 */
    async getLocationList(warehouseId) {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          warehouseId: warehouseId
        };
        const res = await LocationApi.getLocationPage(params);
        this.locationList = res.data.list;
      } catch (error) {
        console.error('获取库位列表失败:', error);
        this.locationList = [];
      }
    },
  }
};
</script>
